<script lang="ts" setup>
import { WxOptionType, Wx } from "@/models/wx";
import { weChatService } from "@/services/wechat.service";
import { searchToJson } from "@/utils/common.methods";
import { onMounted } from "@vue/runtime-core";

const props = withDefaults(defineProps<{ type?: WxOptionType }>(), {
  type: WxOptionType.Default,
});

onMounted(async () => {

  const { type } = props;
  console.log(type);
  if ([WxOptionType.Default].includes(type)) {
    init();
  } else if ([WxOptionType.SnsApiBase].includes(type)) {
    wxLogin();
  } else {
    new Error("Undefined operation, please go to 'h-login-WeChat' to improve the ability")
  }
});

function init(): void {
  const href = location.href.split("?");
  if (href[1]) {
    const locationUrl = searchToJson<{ code: string; state: number }>(href[1]);
    // 登录回调
    let { code, state } = locationUrl;
    state = Number(state);
    if ([WxOptionType.SnsApiBase].includes(state)) {
      // weChatService.empower(code)
    } else {
      console.log("Undefined operation, please go to 'h-login-WeChat' to improve the ability");
    }
  }
}

/** 调起微信授权 */
function wxLogin() {
  if (location.href.split("?")?.length > 1) return;
  Wx.wxLogin(props.type);
}
</script>
<template>
  <slot />
</template>
